package com.jt;



import javax.sound.midi.Soundbank;
import java.nio.file.FileStore;
import java.util.Iterator;

public class TwoLinkedList<T>  implements  Iterable<T> {
    //指向首节点
    private Node first;

    private Node last;

    //元素的大小
    public int size;


    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }


    //内部的节点类
    private class Node<T> {
        //指向上一个节点
        Node<T> lastNode;

        //节点的元素的值
        T t;

        //指向下一个节点
        Node<T> nextNode;

        public Node(Node lastNode, T t, Node nextNode) {
            this.lastNode = lastNode;
            this.t = t;
            this.nextNode = nextNode;
        }

    }

    //查看集合是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    //添加集合的元素
    public void add(T t) {
        final Node l = last;
        Node newNode = new Node(l, t, null);
        this.last = newNode;
        if (l == null)
            first = newNode;
         else
            l.nextNode = newNode;
         size++;

    }

    //删除元素的方式
    public boolean remove(T t) {
        if (first == null) {
            System.out.println("该集合为空");
            return false;
        }

        for (Node currNode = first; currNode != null; currNode = currNode.nextNode) {
            if (currNode.t.equals(t)) {
                //当前节点的下一个节点
                Node nextNode = currNode.nextNode;
                //当前节点的上一个节点
                Node lastNode = currNode.lastNode;

                if (nextNode == null)
                    last = lastNode;
                else {
                    nextNode.lastNode = lastNode;
                }

                if (lastNode == null) {
                    first = nextNode;
                } else {
                    lastNode.nextNode = nextNode;
                }
                size--;
                return true;
            }
        }
        ;
        return false;
    }

    private class MyIterator<T> implements Iterator<T> {
        private Node<T> curNode;

        public MyIterator() {
            this.curNode = first;
        }

        @Override
        public boolean hasNext() {
            if (curNode != null)
                return true;
            else
                return false;
        }

        @Override
        public T next() {
            T t = curNode.t;
            curNode = curNode.nextNode;
            return t;
        }
    }

    //元素进行反转
    public void reverseList() {
        final Node curFist=first;
        final Node curLast=last;


        Node currNode=first;
        for(int  i=0;i<size;i++){
            reverse(currNode);
            currNode=currNode.lastNode;
        }

        this.first=curLast;
        this.last=curFist;


    }

    private void reverse(Node<T> node) {
        final Node<T> lastNode = node.lastNode;
        //下一个节点
        final Node<T> nextNode = node.nextNode;
        node.lastNode = nextNode;
        node.nextNode = lastNode;

    }

}